package com.example.erp;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import jakarta.servlet.http.HttpServletResponse;
import reactor.core.publisher.Flux;

/**
 * openai 对接，在配置文件设定本地 openai(deepseek) 服务地址
 */
@RestController
@RequestMapping("/openai")
public class ChatOpenaiController {

	// 注入模型，配置文件中的模型，或者可以在方法中指定模型
	@Autowired
	private OpenAiChatModel openAiChatModel;

	private final ChatClient chatClient;

//	ChatClient 是使用 ChatClient.Builder 对象创建的
	public ChatOpenaiController(ChatClient.Builder builder) {
		this.chatClient = builder.build();
	}

//	http://localhost:8081/ai/chat?msg=全球有多少个国家  openai api 方式，openai连接信息配置在 application.properties
	@GetMapping("/chat")
	public String chat(@RequestParam(defaultValue = "你好，介绍下你自己吧。") String msg) {
		return this.chatClient.prompt().user(msg).call().content();
	}

	// 流式处理，解决中文乱码有效
	@GetMapping("/chatStream")
	public ResponseEntity<Flux<String>> chat2(@RequestParam(defaultValue = "你好，介绍下你自己吧。") String msg,
			HttpServletResponse response) {
		try {
			response.setCharacterEncoding("UTF-8");// 解决中文乱码
			response.setContentType("text/event-stream;charset=UTF-8");

			Flux<String> streamResponse = chatClient.prompt(msg).stream().content();
			return ResponseEntity.ok(streamResponse);
		} catch (Exception e) {
			return ResponseEntity.badRequest().build();
		}
	}

	@GetMapping("/chatModel")
	public String chat3(@RequestParam(defaultValue = "你好，介绍下你自己吧。") String msg) {
		Prompt prompt = new Prompt(msg);
		return openAiChatModel.call(prompt).getResult().getOutput().getText();
	}

	@GetMapping("/chatModelStream")
	public Flux<String> generateStream(@RequestParam(defaultValue = "你好，介绍下你自己吧。") String msg, HttpServletResponse response) {
		response.setCharacterEncoding("UTF-8");// 解决中文乱码
		
		Prompt prompt = new Prompt(new UserMessage(msg));
		Flux<ChatResponse> streamResponse = this.openAiChatModel.stream(prompt);

		return streamResponse.map(resp -> resp.getResult().getOutput().getText());
	}

}
